﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace CrazyBubbleToolkit
{
    /// <summary>
    /// Interaction logic for BubbleWindow.xaml
    /// </summary>
    public partial class BubbleWindow : Window
    {
        #region 关卡编辑界面数据定义

        private int[] s8BubbleSite;     //记录鼠标点击的泡泡球s8Bubble的坐标

        private Stage UsedStage = null;
        private StageData UsedStageData = null;
        private int RedCount = 0;       //统计已上场红球的个数
        private int YellowCount = 0;
        private int BlueCount = 0;
        private int GreenCount = 0;
        private int PurpleCount = 0;


        private BitmapImage redBubbleImg = new BitmapImage();
        private BitmapImage yellowBubbleImg = new BitmapImage();
        private BitmapImage blueBubbleImg = new BitmapImage();
        private BitmapImage greenBubbleImg = new BitmapImage();
        private BitmapImage purpleBubbleImg = new BitmapImage();

        //新增特殊道具球，分别为星星球1-5，特殊球1-4, 丝带球1-5, 新增6-15
        //-----------------------------------------------------------------------
        private BitmapImage star1BubbleImg = new BitmapImage();
        private BitmapImage star2BubbleImg = new BitmapImage();
        private BitmapImage star3BubbleImg = new BitmapImage();
        private BitmapImage star4BubbleImg = new BitmapImage();
        private BitmapImage star5BubbleImg = new BitmapImage();

        private BitmapImage Silk1BubbleImg = new BitmapImage();
        private BitmapImage Silk2BubbleImg = new BitmapImage();
        private BitmapImage Silk3BubbleImg = new BitmapImage();
        private BitmapImage Silk4BubbleImg = new BitmapImage();
        private BitmapImage Silk5BubbleImg = new BitmapImage();

        private BitmapImage s1BubbleImg = new BitmapImage();
        private BitmapImage s2BubbleImg = new BitmapImage();
        private BitmapImage s3BubbleImg = new BitmapImage();
        private BitmapImage s4BubbleImg = new BitmapImage();
        private BitmapImage s5BubbleImg = new BitmapImage();

        private BitmapImage s6BubbleImg = new BitmapImage();
        private BitmapImage s7BubbleImg = new BitmapImage();
        private BitmapImage s8BubbleImg = new BitmapImage();
        private BitmapImage s9BubbleImg = new BitmapImage();
        private BitmapImage s10BubbleImg = new BitmapImage();

        private BitmapImage s11BubbleImg = new BitmapImage();
        private BitmapImage s12BubbleImg = new BitmapImage();
        private BitmapImage s13BubbleImg = new BitmapImage();
        private BitmapImage s14BubbleImg = new BitmapImage();
        private BitmapImage s15BubbleImg = new BitmapImage();

        private BitmapImage errorImg = new BitmapImage();
        //-----------------------------------------------------------------------

        private BitmapImage blackBubbleImg = new BitmapImage();
        private BitmapImage randomBubbleImg = new BitmapImage();
        private BitmapImage arcaneBubbleImg = new BitmapImage();
        private BitmapImage emptyBubbleImg = new BitmapImage();
        private BitmapImage fogBubbleImg = new BitmapImage();
        private BitmapImage frogBubbleImg = new BitmapImage();
        private BitmapImage thunderBubbleImg = new BitmapImage();
        private BitmapImage xuanwoBubbleImg = new BitmapImage();
        private BitmapImage ghostBubbleImg = new BitmapImage();
        private BitmapImage smallBubbleImg = new BitmapImage();
        private BitmapImage middleBubbleImg = new BitmapImage();
        private BitmapImage largeBubbleImg = new BitmapImage();
        private BitmapImage yesImg = new BitmapImage();
        private BitmapImage noImg = new BitmapImage();
        private BitmapImage ranRedImg = new BitmapImage();
        private BitmapImage ranYellowImg = new BitmapImage();
        private BitmapImage ranBlueImg = new BitmapImage();
        private BitmapImage ranGreenImg = new BitmapImage();
        private BitmapImage ranPurpleImg = new BitmapImage();
        private BitmapImage monkeyImage = new BitmapImage();
        private BitmapImage mouseImage = new BitmapImage();
        private BitmapImage rabbitImage = new BitmapImage();
        private BitmapImage bearImage = new BitmapImage();
        private BitmapImage fishImage = new BitmapImage();


        private Button bubbleButtonInUse = null;

        #endregion


        #region 初始化
        public BubbleWindow()
        {
            InitializeComponent();
            rotateSpeedAngleGroup.Visibility = Visibility.Hidden;  //隐藏炮筒球属性界面

            RanColorCombo.SelectionChanged += RanColorCombo_SelectionChanged;

            redBubbleImg.BeginInit();
            redBubbleImg.UriSource = new Uri("Images/red.png", UriKind.Relative);
            redBubbleImg.EndInit();

            yellowBubbleImg.BeginInit();
            yellowBubbleImg.UriSource = new Uri("Images/yellow.png", UriKind.Relative);
            yellowBubbleImg.EndInit();

            blueBubbleImg.BeginInit();
            blueBubbleImg.UriSource = new Uri("Images/blue.png", UriKind.Relative);
            blueBubbleImg.EndInit();

            greenBubbleImg.BeginInit();
            greenBubbleImg.UriSource = new Uri("Images/green.png", UriKind.Relative);
            greenBubbleImg.EndInit();

            purpleBubbleImg.BeginInit();
            purpleBubbleImg.UriSource = new Uri("Images/purple.png", UriKind.Relative);
            purpleBubbleImg.EndInit();

            //新增道具球star1-5、s1-4, 丝带球1-5, 新增6-15
            //-----------------------------------------------------------------------
            star1BubbleImg.BeginInit();
            star1BubbleImg.UriSource = new Uri("Images/star1.png", UriKind.Relative);
            star1BubbleImg.EndInit();

            star2BubbleImg.BeginInit();
            star2BubbleImg.UriSource = new Uri("Images/star2.png", UriKind.Relative);
            star2BubbleImg.EndInit();

            star3BubbleImg.BeginInit();
            star3BubbleImg.UriSource = new Uri("Images/star3.png", UriKind.Relative);
            star3BubbleImg.EndInit();

            star4BubbleImg.BeginInit();
            star4BubbleImg.UriSource = new Uri("Images/star4.png", UriKind.Relative);
            star4BubbleImg.EndInit();

            star5BubbleImg.BeginInit();
            star5BubbleImg.UriSource = new Uri("Images/star5.png", UriKind.Relative);
            star5BubbleImg.EndInit();


            Silk1BubbleImg.BeginInit();
            Silk1BubbleImg.UriSource = new Uri("Images/Silk1.png", UriKind.Relative);
            Silk1BubbleImg.EndInit();

            Silk2BubbleImg.BeginInit();
            Silk2BubbleImg.UriSource = new Uri("Images/Silk2.png", UriKind.Relative);
            Silk2BubbleImg.EndInit();

            Silk3BubbleImg.BeginInit();
            Silk3BubbleImg.UriSource = new Uri("Images/Silk3.png", UriKind.Relative);
            Silk3BubbleImg.EndInit();

            Silk4BubbleImg.BeginInit();
            Silk4BubbleImg.UriSource = new Uri("Images/Silk4.png", UriKind.Relative);
            Silk4BubbleImg.EndInit();

            Silk5BubbleImg.BeginInit();
            Silk5BubbleImg.UriSource = new Uri("Images/Silk5.png", UriKind.Relative);
            Silk5BubbleImg.EndInit();

            errorImg.BeginInit();
            errorImg.UriSource = new Uri("Images/error.png", UriKind.Relative);
            errorImg.EndInit();


            s1BubbleImg.BeginInit();
            s1BubbleImg.UriSource = new Uri("Images/s1.png", UriKind.Relative);
            s1BubbleImg.EndInit();

            s2BubbleImg.BeginInit();
            s2BubbleImg.UriSource = new Uri("Images/s2.png", UriKind.Relative);
            s2BubbleImg.EndInit();

            s3BubbleImg.BeginInit();
            s3BubbleImg.UriSource = new Uri("Images/s3.png", UriKind.Relative);
            s3BubbleImg.EndInit();

            s4BubbleImg.BeginInit();
            s4BubbleImg.UriSource = new Uri("Images/s4.png", UriKind.Relative);
            s4BubbleImg.EndInit();

            s5BubbleImg.BeginInit();
            s5BubbleImg.UriSource = new Uri("Images/coin.png", UriKind.Relative);
            s5BubbleImg.EndInit();

            //-----------------------------------------------------------------------

            s6BubbleImg.BeginInit();
            s6BubbleImg.UriSource = new Uri("Images/s6.png", UriKind.Relative);
            s6BubbleImg.EndInit();

            s7BubbleImg.BeginInit();
            s7BubbleImg.UriSource = new Uri("Images/s7.png", UriKind.Relative);
            s7BubbleImg.EndInit();

            s8BubbleImg.BeginInit();
            s8BubbleImg.UriSource = new Uri("Images/s8.png", UriKind.Relative);
            s8BubbleImg.EndInit();

            s9BubbleImg.BeginInit();
            s9BubbleImg.UriSource = new Uri("Images/s9.png", UriKind.Relative);
            s9BubbleImg.EndInit();

            s10BubbleImg.BeginInit();
            s10BubbleImg.UriSource = new Uri("Images/s10.png", UriKind.Relative);
            s10BubbleImg.EndInit();


            s11BubbleImg.BeginInit();
            s11BubbleImg.UriSource = new Uri("Images/s11.png", UriKind.Relative);
            s11BubbleImg.EndInit();

            s12BubbleImg.BeginInit();
            s12BubbleImg.UriSource = new Uri("Images/s12.png", UriKind.Relative);
            s12BubbleImg.EndInit();

            s13BubbleImg.BeginInit();
            s13BubbleImg.UriSource = new Uri("Images/s13.png", UriKind.Relative);
            s13BubbleImg.EndInit();

            s14BubbleImg.BeginInit();
            s14BubbleImg.UriSource = new Uri("Images/s14.png", UriKind.Relative);
            s14BubbleImg.EndInit();

            s15BubbleImg.BeginInit();
            s15BubbleImg.UriSource = new Uri("Images/s15.png", UriKind.Relative);
            s15BubbleImg.EndInit();
            //-----------------------------------------------------------------------

            blackBubbleImg.BeginInit();
            blackBubbleImg.UriSource = new Uri("Images/black.png", UriKind.Relative);
            blackBubbleImg.EndInit();

            randomBubbleImg.BeginInit();
            randomBubbleImg.UriSource = new Uri("Images/random.png", UriKind.Relative);
            randomBubbleImg.EndInit();

            arcaneBubbleImg.BeginInit();
            arcaneBubbleImg.UriSource = new Uri("Images/arcane.png", UriKind.Relative);
            arcaneBubbleImg.EndInit();

            emptyBubbleImg.BeginInit();
            emptyBubbleImg.UriSource = new Uri("Images/empty.png", UriKind.Relative);
            emptyBubbleImg.EndInit();

            fogBubbleImg.BeginInit();
            fogBubbleImg.UriSource = new Uri("Images/fog.png", UriKind.Relative);
            fogBubbleImg.EndInit();

            frogBubbleImg.BeginInit();
            frogBubbleImg.UriSource = new Uri("Images/frog.png", UriKind.Relative);
            frogBubbleImg.EndInit();

            thunderBubbleImg.BeginInit();
            thunderBubbleImg.UriSource = new Uri("Images/thunder.png", UriKind.Relative);
            thunderBubbleImg.EndInit();

            xuanwoBubbleImg.BeginInit();
            xuanwoBubbleImg.UriSource = new Uri("Images/xuanwo.png", UriKind.Relative);
            xuanwoBubbleImg.EndInit();

            ghostBubbleImg.BeginInit();
            ghostBubbleImg.UriSource = new Uri("Images/ghost.png", UriKind.Relative);
            ghostBubbleImg.EndInit();

            smallBubbleImg.BeginInit();
            smallBubbleImg.UriSource = new Uri("Images/small.png", UriKind.Relative);
            smallBubbleImg.EndInit();

            middleBubbleImg.BeginInit();
            middleBubbleImg.UriSource = new Uri("Images/middle.png", UriKind.Relative);
            middleBubbleImg.EndInit();

            largeBubbleImg.BeginInit();
            largeBubbleImg.UriSource = new Uri("Images/large.png", UriKind.Relative);
            largeBubbleImg.EndInit();

            yesImg.BeginInit();
            yesImg.UriSource = new Uri("Images/yes.png", UriKind.Relative);
            yesImg.EndInit();

            noImg.BeginInit();
            noImg.UriSource = new Uri("Images/no.png", UriKind.Relative);
            noImg.EndInit();

            ranRedImg.BeginInit();
            ranRedImg.UriSource = new Uri("Images/randomRed.png", UriKind.Relative);
            ranRedImg.EndInit();

            ranYellowImg.BeginInit();
            ranYellowImg.UriSource = new Uri("Images/randomYellow.png", UriKind.Relative);
            ranYellowImg.EndInit();

            ranBlueImg.BeginInit();
            ranBlueImg.UriSource = new Uri("Images/randomBlue.png", UriKind.Relative);
            ranBlueImg.EndInit();

            ranGreenImg.BeginInit();
            ranGreenImg.UriSource = new Uri("Images/randomGreen.png", UriKind.Relative);
            ranGreenImg.EndInit();

            ranPurpleImg.BeginInit();
            ranPurpleImg.UriSource = new Uri("Images/randomPurple.png", UriKind.Relative);
            ranPurpleImg.EndInit();

            monkeyImage.BeginInit();
            monkeyImage.UriSource = new Uri("Images/monkey.png", UriKind.Relative);
            monkeyImage.EndInit();

            mouseImage.BeginInit();
            mouseImage.UriSource = new Uri("Images/mouse.png", UriKind.Relative);
            mouseImage.EndInit();

            rabbitImage.BeginInit();
            rabbitImage.UriSource = new Uri("Images/rabbit.png", UriKind.Relative);
            rabbitImage.EndInit();

            bearImage.BeginInit();
            bearImage.UriSource = new Uri("Images/bear.png", UriKind.Relative);
            bearImage.EndInit();

            fishImage.BeginInit();
            fishImage.UriSource = new Uri("Images/fish.png", UriKind.Relative);
            fishImage.EndInit();


            //22 cols
            for (int i = 0; i < 22; i++)
            {
                BubbleGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            //100 rows
            for (int i = 0; i < 100; i++)
            {
                BubbleGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(32) });
            }

            //fill in the buttons
            for (int row = 0; row < BubbleGrid.RowDefinitions.Count; row++)
            {
                bool isEvenRow = row % 2 == 0;
                int cols = isEvenRow ? BubbleGrid.ColumnDefinitions.Count / 2 : BubbleGrid.ColumnDefinitions.Count / 2 - 1;
                for (int col = 0; col < cols; col++)
                {
                    Button button = new Button { Width = 32, Height = 32 };

                    //add vector info
                    BubbleVector v = new BubbleVector { Row = row, Col = col };
                    button.Tag = v;

                    Grid.SetRow(button, row);
                    Grid.SetColumnSpan(button, 2);
                    Grid.SetColumn(button, isEvenRow ? col * 2 : col * 2 + 1);
                    button.Click += new RoutedEventHandler(Bubble_Click);
                    button.MouseDoubleClick += button_MouseDoubleClick;
                    Grid content = new Grid();

                    //button img
                    Image img = new Image();
                    img.Stretch = Stretch.Fill;
                    img.Source = emptyBubbleImg;

                    //fog img
                    Image fog = new Image() { Visibility = Visibility.Collapsed };
                    fog.Stretch = Stretch.Fill;
                    fog.Source = fogBubbleImg;

                    content.Children.Add(img);
                    content.Children.Add(fog);

                    button.Content = content;

                    BubbleGrid.Children.Add(button);
                }
            }
        }
        #endregion


        #region 界面事件响应

        void button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            /*
            Console.Write("double click");
            //双击清除
            var b = sender as Button;
            var buttonImage = (b.Content as Grid).Children[0] as Image;
            var maskImage = (b.Content as Grid).Children[1] as Image;
            buttonImage.Source = emptyBubbleImg;
            maskImage.Visibility = Visibility.Collapsed;
             * */
        }

        void RanColorCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RefreshCountWarning();
        }

        public void ShowAsDialog(Stage s, StageData ss)
        {
            UsedStage = s;
            ApplyStageData(ss);
            ShowDialog();
        }

        /// <summary>
        /// 移除球，各色球数统计
        /// </summary>
        void HandleBubbleRemoved(ImageSource source)
        {
            bool needRefresh = false;
            if (source == redBubbleImg
                || source == star1BubbleImg
                || source == Silk1BubbleImg
                || source == ranRedImg)
            {
                RedCount--;
                needRefresh = true;
            }
            else if (source == yellowBubbleImg
                || source == star2BubbleImg
                || source == Silk2BubbleImg
                || source == ranYellowImg)
            {
                YellowCount--;
                needRefresh = true;
            }
            else if (source == blueBubbleImg
                || source == star3BubbleImg
                || source == Silk3BubbleImg
                || source == ranBlueImg)
            {
                BlueCount--;
                needRefresh = true;
            }
            else if (source == greenBubbleImg
                || source == star4BubbleImg
                || source == Silk4BubbleImg
                || source == ranGreenImg)
            {
                GreenCount--;
                needRefresh = true;
            }
            else if (source == purpleBubbleImg
                || source == star5BubbleImg
                || source == Silk5BubbleImg
                || source == ranPurpleImg)
            {
                PurpleCount--;
                needRefresh = true;
            }
            if (needRefresh)
                RefreshColorsCountLabel();
        }

        /// <summary>
        /// 点击选择球
        /// </summary>
        private void BubbleUseButton_Click(object sender, RoutedEventArgs e)
        {
            SwitchBubbleButtonInUse(sender as Button);
        }

        /// <summary>
        /// 切换选中的球
        /// </summary>
        void SwitchBubbleButtonInUse(Button button)
        {
            if ("paste" == button.Tag as string)
            {
                if (MessageBox.Show("从系统剪切板粘贴球球数据，会导致当前的球球数据全部被清空，是否继续？"
                    , "警告", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    var json = Clipboard.GetText();
                    StageData ss = null;
                    try
                    {
                        ss = JsonConvert.DeserializeObject<StageData>(json);
                    }
                    catch (Exception)
                    {

                    }
                    if (ss == null)
                    {
                        MessageBox.Show("系统剪切板上没有有效的球球数据！");
                        return;
                    }
                    else
                    {
                        UsedStageData.BubbleGrids = new List<List<Bubble>>();

                        var buttons = BubbleGrid.Children;
                        for (int i = 0; i < buttons.Count; i++)
                        {
                            var b = buttons[i] as Button;
                            var buttonImage = (b.Content as Grid).Children[0] as Image;
                            var maskImage = (b.Content as Grid).Children[1] as Image;
                            buttonImage.Source = emptyBubbleImg;
                            maskImage.Visibility = Visibility.Collapsed;
                        }

                        RedCount = YellowCount = BlueCount = GreenCount = PurpleCount = 0;
                        RefreshColorsCountLabel();

                        ApplyStageData(ss);
                    }
                }
                return;
            }
            else if ("clear" == button.Tag as string)
            {
                if (MessageBox.Show("确定清空所有球球数据？", "警告", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    /////全部清空
                    UsedStageData.BubbleGrids = new List<List<Bubble>>();

                    var buttons = BubbleGrid.Children;
                    for (int i = 0; i < buttons.Count; i++)
                    {
                        var b = buttons[i] as Button;
                        var buttonImage = (b.Content as Grid).Children[0] as Image;
                        var maskImage = (b.Content as Grid).Children[1] as Image;
                        buttonImage.Source = emptyBubbleImg;
                        maskImage.Visibility = Visibility.Collapsed;
                    }

                    RedCount = YellowCount = BlueCount = GreenCount = PurpleCount = 0;
                    RefreshColorsCountLabel();
                }
                return;
            }

            if (button == bubbleButtonInUse)
                return;

            if (bubbleButtonInUse != null)
            {
                bubbleButtonInUse.Background = new SolidColorBrush(Colors.Transparent);
            }

            button.Background = new SolidColorBrush(Colors.LightPink);
            bubbleButtonInUse = button;
        }


        /// <summary>
        /// 添加球，各色球数统计
        /// </summary>
        void HandleBubbleAdded(ImageSource source)
        {
            bool needRefresh = false;
            if (source == redBubbleImg
                || source == star1BubbleImg
                || source == Silk1BubbleImg
                || source == ranRedImg)
            {
                RedCount++;
                needRefresh = true;
            }
            else if (source == yellowBubbleImg
                || source == star2BubbleImg
                || source == Silk2BubbleImg
                || source == ranYellowImg)
            {
                YellowCount++;
                needRefresh = true;
            }
            else if (source == blueBubbleImg
                || source == star3BubbleImg
                || source == Silk3BubbleImg
                || source == ranBlueImg)
            {
                BlueCount++;
                needRefresh = true;
            }
            else if (source == greenBubbleImg
                || source == star4BubbleImg
                || source == Silk4BubbleImg
                || source == ranGreenImg)
            {
                GreenCount++;
                needRefresh = true;
            }
            else if (source == purpleBubbleImg
                || source == star5BubbleImg
                || source == Silk5BubbleImg
                || source == ranPurpleImg)
            {
                PurpleCount++;
                needRefresh = true;
            }
            if (needRefresh)
                RefreshColorsCountLabel();
        }

        void RefreshColorsCountLabel()
        {
            int colorsCount = 0;
            if (RedCount > 0)
            {
                colorsCount++;
                RedCheck.Source = yesImg;
            }
            else
            {
                RedCheck.Source = noImg;
            }
            if (YellowCount > 0)
            {
                colorsCount++;
                YellowCheck.Source = yesImg;
            }
            else
            {
                YellowCheck.Source = noImg;
            }
            if (BlueCount > 0)
            {
                colorsCount++;
                BlueCheck.Source = yesImg;
            }
            else
            {
                BlueCheck.Source = noImg;
            }
            if (GreenCount > 0)
            {
                colorsCount++;
                GreenCheck.Source = yesImg;
            }
            else
            {
                GreenCheck.Source = noImg;
            }
            if (PurpleCount > 0)
            {
                colorsCount++;
                PurpleCheck.Source = yesImg;
            }
            else
            {
                PurpleCheck.Source = noImg;
            }

            ColorsCountLabel.Content = colorsCount.ToString();
            RefreshCountWarning();
        }

        void RefreshCountWarning()
        {
            int rc = RanColorCombo.SelectedIndex + 1;
            if (rc < int.Parse((string)ColorsCountLabel.Content))
            {
                RanColorWarning.Visibility = Visibility.Visible;
            }
            else
            {
                RanColorWarning.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 显示关卡数据ss到界面中
        /// </summary>
        void ApplyStageData(StageData ss)
        {
            if (UsedStageData == null)
            {
                UsedStageData = ss;
            }
            else
            {
                UsedStageData.AnimalGroup = ss.AnimalGroup;
                UsedStageData.BulletBlueRatio = ss.BulletBlueRatio;
                UsedStageData.BulletGreenRatio = ss.BulletGreenRatio;
                UsedStageData.BulletPurpleRatio = ss.BulletPurpleRatio;
                UsedStageData.BulletRedRatio = ss.BulletRedRatio;
                UsedStageData.BulletYellowRatio = ss.BulletYellowRatio;
                UsedStageData.GridsType = ss.GridsType;
                UsedStageData.BubbleGrids = ss.BubbleGrids;
                UsedStageData.Star1 = ss.Star1;
                UsedStageData.Star2 = ss.Star2;
                UsedStageData.Star3 = ss.Star3;
                UsedStageData.TotalBullets = ss.TotalBullets;
                UsedStageData.rotatingSpeedAngle = ss.rotatingSpeedAngle;
            }


            Title = "大头儿子小头爸爸版本-关卡：" + UsedStage.Index + "-" + UsedStage.SubIndex + "，关卡类型：";
            if (UsedStageData.GridsType == 0)
                Title += "收集能量";
            else if (UsedStageData.GridsType == 1)
                Title += "拯救动物";
            else if (UsedStageData.GridsType == 2)
                Title += "击退贱四狼";
            else if (UsedStageData.GridsType == 3)
                Title += "收集能量时间压迫";
            else if (UsedStageData.GridsType == 4)
                Title += "拯救动物时间压迫";
            else
                Title += "未知关卡类型";

            RanColorCombo.SelectedIndex = UsedStageData.RanColors - 1;

            //////////////
            var sgrids = UsedStageData.BubbleGrids;
            if (sgrids != null)
            {
                int bubbleIndex = 0;
                for (int r = 0; r < sgrids.Count; r++)
                {
                    var line = sgrids[r];

                    #region 显示StageGrids中的数据到界面
                    //防范一行出现超过规范个数的情况
                    var maxColCount = (r % 2 == 0) ? Math.Min(11, line.Count) : Math.Min(10, line.Count);
                    for (int col = 0; col < maxColCount; col++)
                    {
                        var bubble = line[col];

                        Button btn = BubbleGrid.Children[bubbleIndex] as Button;
                        Image btnImage = (btn.Content as Grid).Children[0] as Image;
                        Image fogImage = (btn.Content as Grid).Children[1] as Image;

                        switch ((BubbleType)bubble.Type)
                        {
                            case BubbleType.RedBubble:
                                {
                                    btnImage.Source = redBubbleImg;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.YellowBubble:
                                {
                                    btnImage.Source = yellowBubbleImg;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.BlueBubble:
                                {
                                    btnImage.Source = blueBubbleImg;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.GreenBubble:
                                {
                                    btnImage.Source = greenBubbleImg;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.PurpleBubble:
                                {
                                    btnImage.Source = purpleBubbleImg;
                                    PurpleCount++;
                                    break;
                                }

                            //新增特殊道具球，分别为星星球1-5, 丝带球1-5，特殊球1-4
                            //-----------------------------------------------------------------------
                            case BubbleType.star1Bubble:
                                {
                                    btnImage.Source = star1BubbleImg;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.star2Bubble:
                                {
                                    btnImage.Source = star2BubbleImg;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.star3Bubble:
                                {
                                    btnImage.Source = star3BubbleImg;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.star4Bubble:
                                {
                                    btnImage.Source = star4BubbleImg;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.star5Bubble:
                                {
                                    btnImage.Source = star5BubbleImg;
                                    PurpleCount++;
                                    break;
                                }
                            //-------
                            case BubbleType.Silk1Bubble:
                                {
                                    btnImage.Source = Silk1BubbleImg;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.Silk2Bubble:
                                {
                                    btnImage.Source = Silk2BubbleImg;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.Silk3Bubble:
                                {
                                    btnImage.Source = Silk3BubbleImg;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.Silk4Bubble:
                                {
                                    btnImage.Source = Silk4BubbleImg;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.Silk5Bubble:
                                {
                                    btnImage.Source = Silk5BubbleImg;
                                    PurpleCount++;
                                    break;
                                }
                            //-------
                            case BubbleType.s1Bubble:
                                {
                                    btnImage.Source = s1BubbleImg;
                                    break;
                                }
                            case BubbleType.s2Bubble:
                                {
                                    btnImage.Source = s2BubbleImg;
                                    break;
                                }
                            case BubbleType.s3Bubble:
                                {
                                    btnImage.Source = s3BubbleImg;
                                    break;
                                }
                            case BubbleType.s4Bubble:
                                {
                                    btnImage.Source = s4BubbleImg;
                                    break;
                                }
                            case BubbleType.s5Bubble:
                                {
                                    btnImage.Source = s5BubbleImg;
                                    break;
                                }

                            //-------新增6-15
                            case BubbleType.s6Bubble:
                                {
                                    btnImage.Source = s6BubbleImg;
                                    break;
                                }
                            case BubbleType.s7Bubble:
                                {
                                    btnImage.Source = s7BubbleImg;
                                    break;
                                }
                            case BubbleType.s8Bubble:
                                {
                                    btnImage.Source = s8BubbleImg;
                                    break;
                                }
                            case BubbleType.s9Bubble:
                                {
                                    btnImage.Source = s9BubbleImg;
                                    break;
                                }
                            case BubbleType.s10Bubble:
                                {
                                    btnImage.Source = s10BubbleImg;
                                    break;
                                }

                            case BubbleType.s11Bubble:
                                {
                                    btnImage.Source = s11BubbleImg;
                                    break;
                                }
                            case BubbleType.s12Bubble:
                                {
                                    btnImage.Source = s12BubbleImg;
                                    break;
                                }
                            case BubbleType.s13Bubble:
                                {
                                    btnImage.Source = s13BubbleImg;
                                    break;
                                }
                            case BubbleType.s14Bubble:
                                {
                                    btnImage.Source = s14BubbleImg;
                                    break;
                                }
                            case BubbleType.s15Bubble:
                                {
                                    btnImage.Source = s15BubbleImg;
                                    break;
                                }
                            //-----------------------------------------------------------------------

                            case BubbleType.BlackBubble:
                                {
                                    btnImage.Source = blackBubbleImg;
                                    break;
                                }
                            case BubbleType.RanBubble:
                                {
                                    btnImage.Source = randomBubbleImg;
                                    break;
                                }
                            case BubbleType.RanBubble_Red:
                                {
                                    btnImage.Source = ranRedImg;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Yellow:
                                {
                                    btnImage.Source = ranYellowImg;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Blue:
                                {
                                    btnImage.Source = ranBlueImg;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Green:
                                {
                                    btnImage.Source = ranGreenImg;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Purple:
                                {
                                    btnImage.Source = ranPurpleImg;
                                    PurpleCount++;
                                    break;
                                }
                            case BubbleType.RedBubble_Fog:
                                {
                                    btnImage.Source = redBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.YellowBubble_Fog:
                                {
                                    btnImage.Source = yellowBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.BlueBubble_Fog:
                                {
                                    btnImage.Source = blueBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.GreenBubble_Fog:
                                {
                                    btnImage.Source = greenBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.PurpleBubble_Fog:
                                {
                                    btnImage.Source = purpleBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    PurpleCount++;
                                    break;
                                }
                            case BubbleType.BlackBubble_Fog:
                                {
                                    btnImage.Source = blackBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    break;
                                }
                            case BubbleType.RanBubble_Fog:
                                {
                                    btnImage.Source = randomBubbleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    break;
                                }
                            case BubbleType.RanBubble_Red_Fog:
                                {
                                    btnImage.Source = ranRedImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    RedCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Yellow_Fog:
                                {
                                    btnImage.Source = ranYellowImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    YellowCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Blue_Fog:
                                {
                                    btnImage.Source = ranBlueImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    BlueCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Green_Fog:
                                {
                                    btnImage.Source = ranGreenImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    GreenCount++;
                                    break;
                                }
                            case BubbleType.RanBubble_Purple_Fog:
                                {
                                    btnImage.Source = ranPurpleImg;
                                    fogImage.Visibility = Visibility.Visible;
                                    PurpleCount++;
                                    break;
                                }
                            case BubbleType.MonkeyBubble:
                                {
                                    btnImage.Source = monkeyImage;
                                    break;
                                }
                            case BubbleType.MouseBubble:
                                {
                                    btnImage.Source = mouseImage;
                                    break;
                                }
                            case BubbleType.RabbitBubble:
                                {
                                    btnImage.Source = rabbitImage;
                                    break;
                                }
                            case BubbleType.BearBubble:
                                {
                                    btnImage.Source = bearImage;
                                    break;
                                }
                            case BubbleType.FishBubble:
                                {
                                    btnImage.Source = fishImage;
                                    break;
                                }
                            case BubbleType.Empty:
                                {
                                    //btnImage.Source = emptyBubbleImg;
                                    break;
                                }
                            case BubbleType.Frog:
                                {
                                    btnImage.Source = frogBubbleImg;
                                    break;
                                }
                            case BubbleType.Ghost:
                                {
                                    btnImage.Source = ghostBubbleImg;
                                    break;
                                }
                            case BubbleType.Arcane:
                                {
                                    btnImage.Source = arcaneBubbleImg;
                                    break;
                                }
                            case BubbleType.Thunder:
                                {
                                    btnImage.Source = thunderBubbleImg;
                                    break;
                                }
                            case BubbleType.Xuanwo:
                                {
                                    btnImage.Source = xuanwoBubbleImg;
                                    break;
                                }
                            case BubbleType.Animal:
                                {
                                    btnImage.Source = smallBubbleImg;
                                    break;
                                }
                            case BubbleType.MAnimal:
                                {
                                    btnImage.Source = middleBubbleImg;
                                    break;
                                }
                            case BubbleType.MAnimalTop:
                                {
                                    btnImage.Source = middleBubbleImg;
                                    break;
                                }
                            case BubbleType.LAnimal:
                                {
                                    btnImage.Source = largeBubbleImg;
                                    break;
                                }
                            case BubbleType.LAnimalCenter:
                                {
                                    btnImage.Source = largeBubbleImg;
                                    break;
                                }
                            default:
                                {
                                    //出现未定义类型的球数据
                                    line[col] = new Bubble();  //清除该数据
                                    btnImage.Source = errorImg;     //显示为错误图标
                                    break;
                                }

                        }
                        bubbleIndex++;
                    }
                    #endregion
                }
            }

            RefreshColorsCountLabel();
        }

        /// <summary>
        /// 添加使用的球，到界面中的点击位置
        /// </summary>
        void Bubble_Click(object sender, RoutedEventArgs e)
        {
            if (bubbleButtonInUse == null)
            {
                MessageBox.Show("请先选择泡泡类型，再进行操作！");
                return;
            }

            Button btn = sender as Button;
            var v = btn.Tag as BubbleVector;

            Image btnImage = (btn.Content as Grid).Children[0] as Image;
            Image fogImage = (btn.Content as Grid).Children[1] as Image;

            string target = bubbleButtonInUse.Tag as string;

            if (target == "middle")
            {
                /**
                 *   /\
                 *  /  \
                 * /____\
                 * 
                 */
                if (canAddMiddleAnimal(btn))
                {
                    addMiddleAnimal(btn);
                }
                else
                {
                    MessageBox.Show("没有足够的空间添加中动物");
                }
            }
            else if (target == "large")
            {
                /**
                *   ___
                *  /   \
                *  \___/
                */
                if (canAddLargeAnimal(btn))
                {
                    addLargeAnimal(btn);
                }
                else
                {
                    MessageBox.Show("没有足够的空间添加大动物");
                }
            }
            else
            {
                if (btnImage.Source == middleBubbleImg)
                {
                    //////中型动物--->换成其他泡泡
                    if (isMiddleAnimalTopButton(btn))
                    {
                        removeMiddleAnimal(btn);
                    }
                    else
                    {
                        MessageBox.Show("只能对中动物的顶部bubble进行操作");
                        return;
                    }
                }
                else if (btnImage.Source == largeBubbleImg)
                {
                    ///////大型动物---->其他泡泡
                    if (isCenterOfLargeAnimal(btn))
                    {
                        removeLargeAnimal(btn);
                    }
                    else
                    {
                        MessageBox.Show("只能对大动物的中间bubble进行操作");
                        return;
                    }
                }

                HandleBubbleRemoved(btnImage.Source);   //统计球数
                ShowS8BubbleProppety(target, v);        //显示炮筒球的属性

                ////点击球s8时，设置为可见
                //if (target == "s8")
                //{
                //    rotateSpeedAngleGroup.Visibility = Visibility.Visible;  //显示属性界面
                //    s8BubbleSite = new int[]{ v.Row, v.Col };               //记录点击的球s8，坐标位置
                //    rotateSpeedAngleGroup.Header = "炮筒" + "(" + v.Row + ", " + v.Col + ")";

                //    //显示球的速度和角度属性
                //    int[] value = UsedStageData.getRotateSpeedAngle(v.Row, v.Col);
                //    rotateSpeedTextBox.Text = value[0] + "";
                //    rotateAngleTextBox.Text = value[1] + "";
                //}
                //else rotateSpeedAngleGroup.Visibility = Visibility.Hidden;  //隐藏属性界面

                if (target == "red")
                {
                    btnImage.Source = redBubbleImg;
                    UsedStageData.SetBubble(BubbleType.RedBubble, v.Row, v.Col);
                }
                else if (target == "yellow")
                {
                    btnImage.Source = yellowBubbleImg;
                    UsedStageData.SetBubble(BubbleType.YellowBubble, v.Row, v.Col);
                }
                else if (target == "blue")
                {
                    btnImage.Source = blueBubbleImg;
                    UsedStageData.SetBubble(BubbleType.BlueBubble, v.Row, v.Col);
                }
                else if (target == "green")
                {
                    btnImage.Source = greenBubbleImg;
                    UsedStageData.SetBubble(BubbleType.GreenBubble, v.Row, v.Col);
                }
                else if (target == "purple")
                {
                    btnImage.Source = purpleBubbleImg;
                    UsedStageData.SetBubble(BubbleType.PurpleBubble, v.Row, v.Col);
                }

                //新增特殊道具球，分别为星星球1-5，特殊球1-4, 丝带球1-5，新增6-15
                //-----------------------------------------------------------------------
                else if (target == "star1")
                {
                    btnImage.Source = star1BubbleImg;
                    UsedStageData.SetBubble(BubbleType.star1Bubble, v.Row, v.Col);
                }
                else if (target == "star2")
                {
                    btnImage.Source = star2BubbleImg;
                    UsedStageData.SetBubble(BubbleType.star2Bubble, v.Row, v.Col);
                }
                else if (target == "star3")
                {
                    btnImage.Source = star3BubbleImg;
                    UsedStageData.SetBubble(BubbleType.star3Bubble, v.Row, v.Col);
                }
                else if (target == "star4")
                {
                    btnImage.Source = star4BubbleImg;
                    UsedStageData.SetBubble(BubbleType.star4Bubble, v.Row, v.Col);
                }
                else if (target == "star5")
                {
                    btnImage.Source = star5BubbleImg;
                    UsedStageData.SetBubble(BubbleType.star5Bubble, v.Row, v.Col);
                }

                else if (target == "Silk1")
                {
                    btnImage.Source = Silk1BubbleImg;
                    UsedStageData.SetBubble(BubbleType.Silk1Bubble, v.Row, v.Col);
                }
                else if (target == "Silk2")
                {
                    btnImage.Source = Silk2BubbleImg;
                    UsedStageData.SetBubble(BubbleType.Silk2Bubble, v.Row, v.Col);
                }
                else if (target == "Silk3")
                {
                    btnImage.Source = Silk3BubbleImg;
                    UsedStageData.SetBubble(BubbleType.Silk3Bubble, v.Row, v.Col);
                }
                else if (target == "Silk4")
                {
                    btnImage.Source = Silk4BubbleImg;
                    UsedStageData.SetBubble(BubbleType.Silk4Bubble, v.Row, v.Col);
                }
                else if (target == "Silk5")
                {
                    btnImage.Source = Silk5BubbleImg;
                    UsedStageData.SetBubble(BubbleType.Silk5Bubble, v.Row, v.Col);
                }

                else if (target == "s1")
                {
                    btnImage.Source = s1BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s1Bubble, v.Row, v.Col);
                }
                else if (target == "s2")
                {
                    btnImage.Source = s2BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s2Bubble, v.Row, v.Col);
                }
                else if (target == "s3")
                {
                    btnImage.Source = s3BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s3Bubble, v.Row, v.Col);
                }
                else if (target == "s4")
                {
                    btnImage.Source = s4BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s4Bubble, v.Row, v.Col);
                }
                else if (target == "s5")
                {
                    btnImage.Source = s5BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s5Bubble, v.Row, v.Col);
                }

                //------
                else if (target == "s6")
                {
                    btnImage.Source = s6BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s6Bubble, v.Row, v.Col);
                }
                else if (target == "s7")
                {
                    btnImage.Source = s7BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s7Bubble, v.Row, v.Col);
                }
                else if (target == "s8")
                {
                    btnImage.Source = s8BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s8Bubble, v.Row, v.Col);

                }
                else if (target == "s9")
                {
                    btnImage.Source = s9BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s9Bubble, v.Row, v.Col);
                }
                else if (target == "s10")
                {
                    btnImage.Source = s10BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s10Bubble, v.Row, v.Col);
                }

                else if (target == "s11")
                {
                    btnImage.Source = s11BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s11Bubble, v.Row, v.Col);
                }
                else if (target == "s12")
                {
                    btnImage.Source = s12BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s12Bubble, v.Row, v.Col);
                }
                else if (target == "s13")
                {
                    btnImage.Source = s13BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s13Bubble, v.Row, v.Col);
                }
                else if (target == "s14")
                {
                    btnImage.Source = s14BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s14Bubble, v.Row, v.Col);
                }
                else if (target == "s15")
                {
                    btnImage.Source = s15BubbleImg;
                    UsedStageData.SetBubble(BubbleType.s15Bubble, v.Row, v.Col);
                }
                //-----------------------------------------------------------------------

                else if (target == "black")
                {
                    btnImage.Source = blackBubbleImg;
                    UsedStageData.SetBubble(BubbleType.BlackBubble, v.Row, v.Col);
                }
                //else if (target == "random")
                //{
                //    /* 调整浮动面板位置
                //    var pts = btn.PointToScreen(new Point(btn.Width / 2 + 16, btn.Height / 2 - 16));
                //    var stp = ((Panel)RandomCanvas.Parent).PointFromScreen(pts);
                //    RandomCanvas.Margin = new Thickness(stp.X, stp.Y, 0, 0);
                //    RandomCanvas.Visibility = Visibility.Visible;
                //    */

                //    ///////
                //    btnImage.Source = randomBubbleImg;
                //    UsedStageData.SetBubble(BubbleType.RanBubble, v.Row, v.Col);
                //}
                else if (target == "randomRed")
                {
                    btnImage.Source = ranRedImg;
                    UsedStageData.SetBubble(BubbleType.RanBubble_Red, v.Row, v.Col);
                }
                else if (target == "randomYellow")
                {

                    btnImage.Source = ranYellowImg;
                    UsedStageData.SetBubble(BubbleType.RanBubble_Yellow, v.Row, v.Col);

                }
                else if (target == "randomBlue")
                {

                    btnImage.Source = ranBlueImg;
                    UsedStageData.SetBubble(BubbleType.RanBubble_Blue, v.Row, v.Col);

                }
                else if (target == "randomGreen")
                {

                    btnImage.Source = ranGreenImg;
                    UsedStageData.SetBubble(BubbleType.RanBubble_Green, v.Row, v.Col);
                }
                else if (target == "randomPurple")
                {

                    btnImage.Source = ranPurpleImg;
                    UsedStageData.SetBubble(BubbleType.RanBubble_Purple, v.Row, v.Col);
                }
                else if (target == "frog")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = frogBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Frog, v.Row, v.Col);
                }
                else if (target == "fog")
                {
                    ////////////add fog to colorfal bubble////////
                    if (btnImage.Source == emptyBubbleImg)
                    {
                        MessageBox.Show("请先添加普通颜色泡泡（红、黄、蓝、绿、紫、彩虹）");
                    }
                    else if (btnImage.Source == redBubbleImg
                        || btnImage.Source == yellowBubbleImg
                        || btnImage.Source == blueBubbleImg
                        || btnImage.Source == greenBubbleImg
                        || btnImage.Source == purpleBubbleImg
                        || btnImage.Source == ranRedImg
                        || btnImage.Source == ranYellowImg
                        || btnImage.Source == ranBlueImg
                        || btnImage.Source == ranGreenImg
                        || btnImage.Source == ranPurpleImg)
                    {
                        if (fogImage.Visibility == Visibility.Visible)
                            fogImage.Visibility = Visibility.Collapsed;
                        else
                            fogImage.Visibility = Visibility.Visible;
                        UsedStageData.SetBubble((BubbleType)UsedStageData.GetBubble(v.Row, v.Col).Type + 100, v.Row, v.Col);
                    }
                    else
                    {
                        MessageBox.Show("此泡泡类型不允许添加迷雾");
                    }
                }
                else if (target == "arcane")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = arcaneBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Arcane, v.Row, v.Col);
                }
                else if (target == "ghost")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = ghostBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Ghost, v.Row, v.Col);
                }
                else if (target == "xuanwo")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = xuanwoBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Xuanwo, v.Row, v.Col);
                }
                else if (target == "thunder")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = thunderBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Thunder, v.Row, v.Col);
                }
                else if (target == "empty")
                {
                    btnImage.Source = emptyBubbleImg;
                    fogImage.Visibility = Visibility.Collapsed;
                    UsedStageData.SetBubble(BubbleType.Empty, v.Row, v.Col);
                }
                else if (target == "small")
                {
                    fogImage.Visibility = Visibility.Collapsed;
                    btnImage.Source = smallBubbleImg;
                    UsedStageData.SetBubble(BubbleType.Animal, v.Row, v.Col);
                }
                else if (target == "monkey")
                {
                    btnImage.Source = monkeyImage;
                    UsedStageData.SetBubble(BubbleType.MonkeyBubble, v.Row, v.Col);
                }
                else if (target == "mouse")
                {
                    btnImage.Source = mouseImage;
                    UsedStageData.SetBubble(BubbleType.MouseBubble, v.Row, v.Col);
                }
                else if (target == "rabbit")
                {
                    btnImage.Source = rabbitImage;
                    UsedStageData.SetBubble(BubbleType.RabbitBubble, v.Row, v.Col);
                }
                else if (target == "bear")
                {
                    btnImage.Source = bearImage;
                    UsedStageData.SetBubble(BubbleType.BearBubble, v.Row, v.Col);
                }
                else if (target == "fish")
                {
                    btnImage.Source = fishImage;
                    UsedStageData.SetBubble(BubbleType.FishBubble, v.Row, v.Col);
                }
                HandleBubbleAdded(btnImage.Source);
            }
        }


        bool canAddMiddleAnimal(Button topButton)
        {
            Image btnImage = (topButton.Content as Grid).Children[0] as Image;
            if (btnImage.Source != emptyBubbleImg)
                return false;

            var v = topButton.Tag as BubbleVector;

            if (v.Row >= BubbleGrid.RowDefinitions.Count - 1)
                return false;

            if (v.Row % 2 == 0)
            {
                //even row
                if (v.Col == 0 || v.Col >= 10)
                    return false;
            }
            else
            {
                //odd row
            }

            var idxOfTopButton = BubbleGrid.Children.IndexOf(topButton);
            var blButton = BubbleGrid.Children[idxOfTopButton + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfTopButton + 11] as Button;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            if (blImage.Source != emptyBubbleImg)
                return false;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            if (brImage.Source != emptyBubbleImg)
                return false;

            return true;
        }
        bool canAddLargeAnimal(Button centerButton)
        {
            var centerImage = (centerButton.Content as Grid).Children[0] as Image;
            if (centerImage.Source != emptyBubbleImg)
                return false;

            var v = centerButton.Tag as BubbleVector;
            if (v.Row == 0 || v.Row >= BubbleGrid.RowDefinitions.Count - 1)
                return false;

            if (v.Col == 0)
                return false;

            if (v.Row % 2 == 0)
            {
                //even row
                if (v.Col >= 10)
                    return false;
            }
            else
            {
                //odd row
                if (v.Col >= 9)
                    return false;
            }

            var idxOfCenter = BubbleGrid.Children.IndexOf(centerButton);

            var tlButton = BubbleGrid.Children[idxOfCenter - 11] as Button;
            var trButton = BubbleGrid.Children[idxOfCenter - 10] as Button;
            var lButton = BubbleGrid.Children[idxOfCenter - 1] as Button;
            var rButton = BubbleGrid.Children[idxOfCenter + 1] as Button;
            var blButton = BubbleGrid.Children[idxOfCenter + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfCenter + 11] as Button;

            Image tlImage = (tlButton.Content as Grid).Children[0] as Image;
            if (tlImage.Source != emptyBubbleImg)
                return false;

            Image trImage = (trButton.Content as Grid).Children[0] as Image;
            if (trImage.Source != emptyBubbleImg)
                return false;

            Image lImage = (lButton.Content as Grid).Children[0] as Image;
            if (lImage.Source != emptyBubbleImg)
                return false;

            Image rImage = (rButton.Content as Grid).Children[0] as Image;
            if (rImage.Source != emptyBubbleImg)
                return false;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            if (blImage.Source != emptyBubbleImg)
                return false;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            if (brImage.Source != emptyBubbleImg)
                return false;

            return true;
        }

        bool isCenterOfLargeAnimal(Button button)
        {
            var centerImage = (button.Content as Grid).Children[0] as Image;
            if (centerImage.Source != largeBubbleImg)
                return false;

            var v = button.Tag as BubbleVector;
            if (v.Row == 0 || v.Row >= BubbleGrid.RowDefinitions.Count - 1)
                return false;
            if (v.Row % 2 == 0)
            {
                //even row
                if (v.Col >= 10)
                    return false;
            }
            else
            {
                //odd row
                if (v.Col >= 9)
                    return false;
            }

            var idxOfCenter = BubbleGrid.Children.IndexOf(button);

            var tlButton = BubbleGrid.Children[idxOfCenter - 11] as Button;
            var trButton = BubbleGrid.Children[idxOfCenter - 10] as Button;
            var lButton = BubbleGrid.Children[idxOfCenter - 1] as Button;
            var rButton = BubbleGrid.Children[idxOfCenter + 1] as Button;
            var blButton = BubbleGrid.Children[idxOfCenter + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfCenter + 11] as Button;

            Image tlImage = (tlButton.Content as Grid).Children[0] as Image;
            if (tlImage.Source != largeBubbleImg)
                return false;

            Image trImage = (trButton.Content as Grid).Children[0] as Image;
            if (trImage.Source != largeBubbleImg)
                return false;

            Image lImage = (lButton.Content as Grid).Children[0] as Image;
            if (lImage.Source != largeBubbleImg)
                return false;

            Image rImage = (rButton.Content as Grid).Children[0] as Image;
            if (rImage.Source != largeBubbleImg)
                return false;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            if (blImage.Source != largeBubbleImg)
                return false;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            if (brImage.Source != largeBubbleImg)
                return false;

            return true;
        }

        void addMiddleAnimal(Button topButton)
        {
            Image topImage = (topButton.Content as Grid).Children[0] as Image;
            var v = topButton.Tag as BubbleVector;
            var idxOfTopButton = BubbleGrid.Children.IndexOf(topButton);
            var blButton = BubbleGrid.Children[idxOfTopButton + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfTopButton + 11] as Button;
            var blV = blButton.Tag as BubbleVector;
            var brV = brButton.Tag as BubbleVector;


            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            Image brImage = (brButton.Content as Grid).Children[0] as Image;

            topImage.Source = middleBubbleImg;
            blImage.Source = middleBubbleImg;
            brImage.Source = middleBubbleImg;

            UsedStageData.SetBubble(BubbleType.MAnimalTop, v.Row, v.Col);
            UsedStageData.SetBubble(BubbleType.MAnimal, blV.Row, blV.Col);
            UsedStageData.SetBubble(BubbleType.MAnimal, brV.Row, brV.Col);
        }
        void addLargeAnimal(Button centerButton)
        {
            var centerImage = (centerButton.Content as Grid).Children[0] as Image;
            centerImage.Source = largeBubbleImg;

            var v = centerButton.Tag as BubbleVector;

            var idxOfCenter = BubbleGrid.Children.IndexOf(centerButton);

            var tlButton = BubbleGrid.Children[idxOfCenter - 11] as Button;
            var trButton = BubbleGrid.Children[idxOfCenter - 10] as Button;
            var lButton = BubbleGrid.Children[idxOfCenter - 1] as Button;
            var rButton = BubbleGrid.Children[idxOfCenter + 1] as Button;
            var blButton = BubbleGrid.Children[idxOfCenter + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfCenter + 11] as Button;

            var tlV = tlButton.Tag as BubbleVector;
            var trV = trButton.Tag as BubbleVector;
            var lV = lButton.Tag as BubbleVector;
            var rV = rButton.Tag as BubbleVector;
            var blV = blButton.Tag as BubbleVector;
            var brV = brButton.Tag as BubbleVector;

            Image tlImage = (tlButton.Content as Grid).Children[0] as Image;
            tlImage.Source = largeBubbleImg;

            Image trImage = (trButton.Content as Grid).Children[0] as Image;
            trImage.Source = largeBubbleImg;

            Image lImage = (lButton.Content as Grid).Children[0] as Image;
            lImage.Source = largeBubbleImg;

            Image rImage = (rButton.Content as Grid).Children[0] as Image;
            rImage.Source = largeBubbleImg;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            blImage.Source = largeBubbleImg;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            brImage.Source = largeBubbleImg;

            UsedStageData.SetBubble(BubbleType.LAnimalCenter, v.Row, v.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, tlV.Row, tlV.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, trV.Row, trV.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, lV.Row, lV.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, rV.Row, rV.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, blV.Row, blV.Col);
            UsedStageData.SetBubble(BubbleType.LAnimal, brV.Row, brV.Col);
        }

        void removeMiddleAnimal(Button topButton)
        {
            Image topImage = (topButton.Content as Grid).Children[0] as Image;
            var v = topButton.Tag as BubbleVector;
            var idxOfTopButton = BubbleGrid.Children.IndexOf(topButton);
            var blButton = BubbleGrid.Children[idxOfTopButton + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfTopButton + 11] as Button;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            Image brImage = (brButton.Content as Grid).Children[0] as Image;

            var blV = blButton.Tag as BubbleVector;
            var brV = brButton.Tag as BubbleVector;

            topImage.Source = emptyBubbleImg;
            blImage.Source = emptyBubbleImg;
            brImage.Source = emptyBubbleImg;

            UsedStageData.SetBubble(BubbleType.Empty, v.Row, v.Col);
            UsedStageData.SetBubble(BubbleType.Empty, blV.Row, blV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, brV.Row, brV.Col);
        }
        void removeLargeAnimal(Button centerButton)
        {
            var centerImage = (centerButton.Content as Grid).Children[0] as Image;
            centerImage.Source = emptyBubbleImg;

            var v = centerButton.Tag as BubbleVector;

            var idxOfCenter = BubbleGrid.Children.IndexOf(centerButton);

            var tlButton = BubbleGrid.Children[idxOfCenter - 11] as Button;
            var trButton = BubbleGrid.Children[idxOfCenter - 10] as Button;
            var lButton = BubbleGrid.Children[idxOfCenter - 1] as Button;
            var rButton = BubbleGrid.Children[idxOfCenter + 1] as Button;
            var blButton = BubbleGrid.Children[idxOfCenter + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfCenter + 11] as Button;

            var tlV = tlButton.Tag as BubbleVector;
            var trV = trButton.Tag as BubbleVector;
            var lV = lButton.Tag as BubbleVector;
            var rV = rButton.Tag as BubbleVector;
            var blV = blButton.Tag as BubbleVector;
            var brV = brButton.Tag as BubbleVector;

            Image tlImage = (tlButton.Content as Grid).Children[0] as Image;
            tlImage.Source = emptyBubbleImg;

            Image trImage = (trButton.Content as Grid).Children[0] as Image;
            trImage.Source = emptyBubbleImg;

            Image lImage = (lButton.Content as Grid).Children[0] as Image;
            lImage.Source = emptyBubbleImg;

            Image rImage = (rButton.Content as Grid).Children[0] as Image;
            rImage.Source = emptyBubbleImg;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            blImage.Source = emptyBubbleImg;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            brImage.Source = emptyBubbleImg;

            UsedStageData.SetBubble(BubbleType.Empty, v.Row, v.Col);
            UsedStageData.SetBubble(BubbleType.Empty, tlV.Row, tlV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, trV.Row, trV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, lV.Row, lV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, rV.Row, rV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, blV.Row, blV.Col);
            UsedStageData.SetBubble(BubbleType.Empty, brV.Row, brV.Col);
        }

        bool isMiddleAnimalTopButton(Button button)
        {
            Image btnImage = (button.Content as Grid).Children[0] as Image;
            if (btnImage.Source != middleBubbleImg)
                return false;

            var v = button.Tag as BubbleVector;

            if (v.Row >= BubbleGrid.RowDefinitions.Count - 1)
                return false;

            if (v.Row % 2 == 0)
            {
                //even row
                if (v.Col >= 10)
                    return false;
            }
            else
            {
                //odd row
            }

            var idxOfTopButton = BubbleGrid.Children.IndexOf(button);
            var blButton = BubbleGrid.Children[idxOfTopButton + 10] as Button;
            var brButton = BubbleGrid.Children[idxOfTopButton + 11] as Button;

            Image blImage = (blButton.Content as Grid).Children[0] as Image;
            if (blImage.Source != middleBubbleImg)
                return false;

            Image brImage = (brButton.Content as Grid).Children[0] as Image;
            if (brImage.Source != middleBubbleImg)
                return false;

            return true;
        }

        private void propertyButton_Click(object sender, RoutedEventArgs e)
        {
            var pw = new PropertyWindow();
            pw.ShowAsDialog(UsedStageData);

            Title = "萌宠泡泡星-关卡：" + UsedStage.Index + "-" + UsedStage.SubIndex + "，关卡类型：";
            if (UsedStageData.GridsType == 0)
                Title += "收集能量";
            else if (UsedStageData.GridsType == 1)
                Title += "拯救动物";
            else if (UsedStageData.GridsType == 2)
                Title += "击退贱四狼";
            else if (UsedStageData.GridsType == 3)
                Title += "收集能量时间压迫";
            else if (UsedStageData.GridsType == 4)
                Title += "拯救动物时间压迫";
            else
                Title += "未知关卡类型";
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            //校验数据是否合法
            if (RanColorWarning.Visibility == Visibility.Visible)
            {
                MessageBox.Show("嘿，你丫先把配置冲突解决了再提交成不成，成不成？！");
                return;
            }

            UsedStageData.UsedColors.Clear();
            if (RedCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.RedBubble);
            if (YellowCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.YellowBubble);
            if (BlueCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.BlueBubble);
            if (GreenCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.GreenBubble);
            if (PurpleCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.PurpleBubble);


            (sender as Button).IsEnabled = false;
            WaitingFrame.Visibility = Visibility.Visible;
            WaitingText.Visibility = Visibility.Visible;

            var http = new HttpClient();
            var req = new HttpRequestMessage(HttpMethod.Post, "http://czpanda.com:3099/save");

            var queryBuilder = new QueryStringBuilder();
            queryBuilder.Add("v", "1");
            queryBuilder.Add("s1", (int.Parse(UsedStage.Index) - 1).ToString());
            queryBuilder.Add("s2", (int.Parse(UsedStage.SubIndex) - 1).ToString());

            UsedStageData.RanColors = RanColorCombo.SelectedIndex + 1;

            UsedStageData.Compress();
            var sdJson = JsonConvert.SerializeObject(UsedStageData);
            //将{"t":0}替换成{}，进一步压缩json体积
            var emptyStageBubbleJson = JsonConvert.SerializeObject(new Bubble());
            sdJson = sdJson.Replace(emptyStageBubbleJson, "{}");
            queryBuilder.Add("d", sdJson);

            var query = queryBuilder.ToQueryString(false);

            req.Content = new StringContent(query, Encoding.UTF8);
            req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            try
            {
                http.SendAsync(req).ContinueWith(t =>
                {
                    var resp = t.Result;
                    resp.Content.ReadAsStringAsync().ContinueWith(tt =>
                    {
                        var body = tt.Result;

                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            if (body == "Ok")
                            {
                                MessageBox.Show("提交成功");
                            }
                            else
                            {
                                MessageBox.Show("提交失败");
                            }

                            (sender as Button).IsEnabled = true;
                            WaitingFrame.Visibility = Visibility.Collapsed;
                            WaitingText.Visibility = Visibility.Collapsed;

                        }));

                    });
                });

            }
            catch (Exception)
            {
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void RanMainColorButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            RandomCanvas.Visibility = Visibility.Collapsed;
        }
        #endregion


        #region 本地保存数据处理逻辑
        //=======================================================
        //保存数据到文件
        //=======================================================
        /// <summary>
        /// 保存数据data到文件，返回值为保存的文件名
        /// </summary>
        public string SaveToFile(String data, String name, bool mute)
        {
            String filePath = "";

            //若未命名，则使用系统时间自动命名
            if (name == null || name.Trim().Equals("（重命名）") || name.Trim().Equals(""))
            {
                name = DateTime.Now.ToLongTimeString().Replace(":", ".");   //使用系统时间自动为文件命名
                filePath = SaveToFile(data, name, mute);                    //保存数据到文件
                return filePath;                                            //返回保存的文件名
            }

            try
            {
                filePath = SaveProcess(data, name);                         //保存数据并记录文件完整路径

                if (!mute) MessageBox.Show("成功导出数据到:“" + filePath + "”!");
                return filePath;
            }
            catch (Exception)
            {
                MessageBox.Show("保存数据失败");
                return "";
            }
        }

        /// <summary>
        /// 保存数据data到文件处理过程，返回值为保存的文件名
        /// </summary>
        public String SaveProcess(String data, String name)
        {
            string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Date.ToString("yyyy_MM_dd") + @"导出\";         //设置当前目录
            if (!System.IO.Directory.Exists(CurDir)) System.IO.Directory.CreateDirectory(CurDir);   //该路径不存在时，在当前文件目录下创建文件夹"导出.."

            //不存在该文件时先创建
            String filePath = CurDir + name + ".json";
            System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false);     //文件已覆盖方式添加内容

            file1.Write(data);                                                              //保存数据到文件

            file1.Close();                                                                  //关闭文件
            file1.Dispose();                                                                //释放对象

            return filePath;
        }

        /// <summary>
        /// 保存数据data到原文件filePathName中
        /// </summary>
        public String SaveToNativeFile(String data, String filePathName, bool mute)
        {
            try
            {
                if (!System.IO.Directory.Exists(filePathName)) return SaveToFile(data, filePathName, mute);

                System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePathName, false); //文件已覆盖方式添加内容
                file1.Write(data);                                                              //保存数据到文件

                file1.Close();                                                                  //关闭文件
                file1.Dispose();                                                                //释放对象

                if (!mute) MessageBox.Show("成功导出数据到:“" + filePathName + "”!");
                return filePathName;
            }
            catch (Exception)
            {
                return SaveToFile(data, filePathName, mute);          //若保存到原文件失败，则创建新文件进行保存
            }
        }

        //获取当前编辑关卡数据
        private string getLevelData()
        {
            //校验数据是否合法
            if (RanColorWarning.Visibility == Visibility.Visible)
            {
                MessageBox.Show("嘿，你丫先把配置冲突解决了再提交成不成，成不成？！");
                return "";
            }

            UsedStageData.UsedColors.Clear();
            if (RedCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.RedBubble);
            if (YellowCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.YellowBubble);
            if (BlueCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.BlueBubble);
            if (GreenCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.GreenBubble);
            if (PurpleCount > 0)
                UsedStageData.UsedColors.Add((int)BubbleType.PurpleBubble);


            UsedStageData.RanColors = RanColorCombo.SelectedIndex + 1;

            UsedStageData.Compress();
            var sdJson = JsonConvert.SerializeObject(UsedStageData);
            //将{"t":0}替换成{}，进一步压缩json体积
            var emptyStageBubbleJson = JsonConvert.SerializeObject(new Bubble());
            sdJson = sdJson.Replace(emptyStageBubbleJson, "{}");

            return sdJson;
        }

        //添加数据到本地
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            nativeDataSave(1);
            return;

            string leveldata = getLevelData();
            if (leveldata.Equals("")) return;

            //保存数据到本地
            string data = MainWindow.levelData.Trim();
            data = data.Replace("]]}", "," + leveldata + "]]}");        //保存到关卡数据

            SaveToNativeFile(data, textBoxName.Text.Trim(), false);     //保存到文件
            MainWindow.levelData = data;

        }

        //替换当前关卡数据
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            nativeDataSave(2);
            return;

            string leveldata = getLevelData();
            if (leveldata.Equals("")) return;

            //保存数据到本地
            string data = MainWindow.levelData.Trim();
            data = data.Replace("]]}", "");                             //保存到关卡数据
            data = data.Replace("{\"gt\":", "#{\"gt\":");               //添加特殊分割符#
            string[] datas = data.Split('#');                           //对关卡数据进行分割处理，datas[0]不是关卡数据

            datas[MainWindow.levelIndex] = leveldata + (MainWindow.levelIndex == datas.Length - 1 ? "" : ",");

            data = "";
            for (int i = 0; i < datas.Length; i++) data += datas[i];
            data += "]]}";

            SaveToNativeFile(data, textBoxName.Text.Trim(), true);     //保存到文件
            MessageBox.Show("关卡数据已替换");

            //更新显示信息
            Close();
            MainWindow.Instance.dataInput(data);
        }

        //删除当前关卡数据
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            nativeDataSave(3);
            return;

            string leveldata = getLevelData();
            if (leveldata.Equals("")) return;

            //保存数据到本地
            string data = MainWindow.levelData.Trim();
            data = data.Replace("]]}", "");                             //保存到关卡数据
            data = data.Replace("{\"gt\":", "#{\"gt\":");               //添加特殊分割符#
            string[] datas = data.Split('#');                           //对关卡数据进行分割处理，datas[0]不是关卡数据

            data = "";
            for (int i = 0; i < datas.Length; i++)
            {
                if (i == MainWindow.levelIndex) continue;
                data += datas[i];
            }
            data += "]]}";
            if (MainWindow.levelIndex == datas.Length - 1) data = data.Replace(",]]}", "]]}");

            SaveToNativeFile(data, textBoxName.Text.Trim(), true);     //保存到文件
            MessageBox.Show("关卡数据已删除");

            //更新显示信息
            Close();
            MainWindow.Instance.dataInput(data);
        }

        private void nativeDataSave(int index)
        {
            string leveldata = getLevelData();          //获取当前关卡数据
            if (leveldata.Equals("")) return;

            string data = MainWindow.levelData.Trim();  //获取所有关卡数据


            if (index == 1)             //添加
            {
                //保存数据到本地
                data = data.Replace("]]}", "," + leveldata + "]]}");        //保存到关卡数据
                //fileName = SaveToNativeFile(data, textBoxName.Text.Trim(), false);     //保存到文件
            }
            else
            {
                data = data.Replace("]]}", "");                             //保存到关卡数据
                data = data.Replace("{\"gt\":", "#{\"gt\":");               //添加特殊分割符#
                string[] datas = data.Split('#');                           //对关卡数据进行分割处理，datas[0]不是关卡数据

                if (index == 2)         //替换
                {
                    datas[MainWindow.levelIndex] = leveldata + (MainWindow.levelIndex == datas.Length - 1 ? "" : ",");

                    data = "";
                    for (int i = 0; i < datas.Length; i++) data += datas[i];
                    data += "]]}";

                    //fileName = SaveToNativeFile(data, textBoxName.Text.Trim(), false);     //保存到文件
                    //MessageBox.Show("关卡数据已替换");
                }
                else if (index == 3)    //删除
                {
                    data = "";
                    for (int i = 0; i < datas.Length; i++)
                    {
                        if (i == MainWindow.levelIndex) continue;
                        data += datas[i];
                    }
                    data += "]]}";
                    if (MainWindow.levelIndex == datas.Length - 1) data = data.Replace(",]]}", "]]}");

                    //fileName = SaveToNativeFile(data, textBoxName.Text.Trim(), false);     //保存到文件
                    //MessageBox.Show("关卡数据已删除");
                }
                else if (index == 4)      //分文件导出
                {
                    int num = 20;           //每20关导出为一个文件
                    try { num = int.Parse(textBoxNum.Text.Trim()); }
                    catch (Exception Ex) { };

                    string fileName = "";
                    string nameTmp = "";
                    string data2 = "[";
                    for (int i = 1; i < datas.Length; i++)
                    {
                        datas[i] = levelTrim(datas[i]);             //仅获取关卡数据部分
                        data2 += datas[i];
                        if (i % num == 0 || i == datas.Length - 1)
                        {
                            data2 += "]";

                            nameTmp = SaveToNativeFile(data2, textBoxName.Text.Trim(), true); //保存到文件
                            nameTmp = System.IO.Path.GetFileNameWithoutExtension(nameTmp);     //保存的文件名
                            if (fileName.Equals("")) fileName = nameTmp;                         //仅记录一次文件名

                            if (i < datas.Length - 1) textBoxName.Text = fileName + "_" + (int)(i / num + 1);            //新文件名

                            data2 = "[";
                        }
                        else data2 += ",";   //关卡数据分割符
                    }
                    MessageBox.Show("导出数据保存为: " + fileName + " - " + textBoxName.Text);
                }
            }
            if (index <= 3)
            {
                SaveToNativeFile(data, textBoxName.Text.Trim(), false);     //保存到文件

                //更新显示信息
                Close();
                MainWindow.Instance.dataInput2(data);
            }


        }

        //获取关卡数据
        private string levelTrim(string levelData)
        {
            string tmp = levelData.Substring(levelData.Length - 3, 3);
            if (tmp.Equals("],[")) levelData = levelData.Substring(0, levelData.Length - 3);//去除串尾部"],["
            tmp = levelData.Substring(levelData.Length - 1, 1);
            if (tmp.Equals(",")) levelData = levelData.Substring(0, levelData.Length - 1);//去除串尾部","
            tmp = levelData.Substring(levelData.Length - 1, 1);
            if (tmp.Equals("]")) levelData = levelData.Substring(0, levelData.Length - 1);//去除串尾部"]"

            return levelData;
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            nativeDataSave(4);
        }
        
        #endregion


        #region 炮筒球属性相关操作

        //记录速度和角度数据到StageData中
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (s8BubbleSite != null)
            {
                UsedStageData.updateRotateSpeedAngleAttr(s8BubbleSite[0], s8BubbleSite[1], rotateSpeedTextBox.Text, rotateAngleTextBox.Text);
            }
        }

        //判断点击的球是否为炮筒球。若是，则显示其对应的属性；不是，则不显示
        private void ShowS8BubbleProppety(string target, BubbleVector v)
        {
            //点击球s8时，设置为可见
            if (target == "s8")
            {
                rotateSpeedAngleGroup.Visibility = Visibility.Visible;  //显示属性界面
                s8BubbleSite = new int[] { v.Row, v.Col };               //记录点击的球s8，坐标位置
                rotateSpeedAngleGroup.Header = "炮筒" + "(" + v.Row + ", " + v.Col + ")";

                //显示球的速度和角度属性
                int[] value = UsedStageData.getRotateSpeedAngle(v.Row, v.Col);
                rotateSpeedTextBox.Text = value[0] + "";
                rotateAngleTextBox.Text = value[1] + "";
            }
            else
            {
                rotateSpeedAngleGroup.Visibility = Visibility.Hidden;  //隐藏属性界面
                UsedStageData.RemoveRotateSpeedAngleAttr(v.Row, v.Col);//移除坐标处的炮筒球属性
            }
        }
        #endregion

    }
    

    class BubbleVector
    {
        public int Row { get; set; }
        public int Col { get; set; }
    }
}
